#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版数据库初始化脚本
"""

import os
import sys
import asyncio
import logging
from pathlib import Path

# 设置环境变量
os.environ.setdefault('SECRET_KEY', 'crm-development-secret-key-change-in-production-minimum-32-chars')
os.environ.setdefault('DEBUG', 'true')
os.environ.setdefault('DATABASE_URL', 'sqlite+aiosqlite:///./data/crm_tourism.db')

# 确保数据目录存在
data_dir = Path('./data')
data_dir.mkdir(exist_ok=True)

# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

async def init_database():
    """初始化数据库"""
    try:
        from src.models.base import Base
        from src.models.rbac import User, Role, Permission, UserRole, RolePermission
        from sqlalchemy.ext.asyncio import create_async_engine
        from datetime import datetime
        
        logger.info("🚀 开始初始化数据库...")
        
        # 创建数据库引擎
        engine = create_async_engine(
            "sqlite+aiosqlite:///./data/crm_tourism.db",
            echo=True
        )
        
        # 创建所有表
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)
        
        logger.info("✅ 数据库表创建成功")
        
        # 创建基础数据
        from sqlalchemy.ext.asyncio import AsyncSession
        
        async with AsyncSession(engine) as session:
            # 检查是否已有用户
            from sqlalchemy import select
            result = await session.execute(select(User).limit(1))
            existing_user = result.scalar_one_or_none()
            
            if not existing_user:
                logger.info("📝 创建基础数据...")
                
                # 创建管理员角色
                admin_role = Role(
                    name="admin",
                    description="系统管理员",
                    is_active=True
                )
                session.add(admin_role)
                await session.flush()
                
                # 创建管理员用户
                from src.auth.jwt_auth import password_manager
                admin_password = "admin123"  # 默认密码
                hashed_password = password_manager.hash_password(admin_password)
                
                admin_user = User(
                    username="admin",
                    real_name="系统管理员",
                    email="admin@crm.com",
                    password_hash=hashed_password,
                    is_active=True,
                    is_superuser=True,
                    created_at=datetime.utcnow(),
                    updated_at=datetime.utcnow()
                )
                session.add(admin_user)
                await session.flush()
                
                # 分配角色给用户
                user_role = UserRole(
                    user_id=admin_user.id,
                    role_id=admin_role.id
                )
                session.add(user_role)
                
                await session.commit()
                
                logger.info(f"✅ 管理员账户创建成功 - 用户名: admin, 密码: {admin_password}")
            else:
                logger.info("ℹ️  用户数据已存在，跳过创建")
        
        # 关闭引擎
        await engine.dispose()
        
        logger.info("✅ 数据库初始化完成！")
        return True
        
    except Exception as e:
        logger.error(f"❌ 数据库初始化失败: {e}")
        import traceback
        traceback.print_exc()
        return False

async def main():
    """主函数"""
    print("="*60)
    print("🏗️  CRM 数据库初始化工具")
    print("="*60)
    
    success = await init_database()
    
    if success:
        print("="*60)
        print("✅ 数据库初始化完成！")
        print("📁 数据库文件: ./data/crm_tourism.db")
        print("👤 管理员账户: admin / admin123")
        print("🚀 现在可以启动Web服务: python3 start_backend.py")
        print("="*60)
    else:
        print("❌ 数据库初始化失败")
    
    return success

if __name__ == "__main__":
    try:
        result = asyncio.run(main())
        sys.exit(0 if result else 1)
    except KeyboardInterrupt:
        print("\n👋 初始化已取消")
        sys.exit(1)
    except Exception as e:
        logger.error(f"❌ 程序异常: {e}")
        sys.exit(1)